<template>
  <div class="shipudetail">
    <div class="modal-content">
      <div class="modal-header">
        <h3>{{ recipe.name || '食谱详情' }}</h3>
        <button @click="$emit('close')" class="close-btn">×</button>
      </div>
      <div class="food-info">
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="error" class="error">{{ error }}</div>
        <div v-else>
          <!-- 图片展示区域 -->
          <div class="food-image-container">
            <img 
              :src="recipe.url || defaultImage" 
              alt="食谱图片" 
              class="food-image"
              @error="handleImageError"
            >
            <div v-if="imageError" class="image-error">图片加载失败，点击刷新</div>
          </div>

          <!-- 食谱信息 -->
          <div class="nutritional-info">
            <p><strong>描述:</strong> {{ recipe.description }}</p>
            <p><strong>烹饪方法:</strong> {{ recipe.cooking_method }}</p>
            <p><strong>推荐人:</strong> 营养师（ID: {{ recipe.recommended_by }}）</p>
          </div>

          <!-- 关联食物列表 -->
          <div class="used-foods">
            <h4>所用到的食物:</h4>
            <ul v-if="usedFoods.length > 0">
              <li v-for="(item, index) in usedFoods" :key="index">
                {{ item.foodName }} - {{ item.quantity }} {{ item.unit }}
                <span v-if="item.processingMethod">（处理方法: {{ item.processingMethod }}）</span>
              </li>
            </ul>
            <p v-else class="empty-foods">暂无食物信息</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, computed } from 'vue';
import axios from 'axios';

const props = defineProps({
  recipeId: { type: Number, required: true }
});
const emit = defineEmits(['close']);

// 数据状态
const recipe = ref({});
const usedFoods = ref([]);
const loading = ref(true);
const error = ref('');
const imageError = ref(false);
const defaultImage = 'https://picsum.photos/200/150'; // 默认图片地址

// 计算属性：处理recipeId类型
const recipeId = computed(() => Number(props.recipeId));

// 获取数据流程
axios.get(`http://localhost:8080/MDMS0214_war/recipe/all`)
  .then(recipeRes => {
    // 查找当前食谱
    const targetRecipe = recipeRes.data.find(r => r.recipe_id === recipeId.value);
    if (!targetRecipe) throw new Error('食谱不存在');
    
    recipe.value = targetRecipe;
    
    // 获取食谱-食物关联数据（注意接口路径为 recipe_food/all）
    return axios.get(`http://localhost:8080/MDMS0214_war/recipe_food/all`);
  })
  .then(recipeFoodRes => {
    // 过滤当前食谱的关联记录
    const matchedRecipeFoods = recipeFoodRes.data.filter(
      rf => rf.recipe_id === recipeId.value
    );
    
    if (matchedRecipeFoods.length === 0) {
      usedFoods.value = [];
      loading.value = false;
      return;
    }
    
    // 提取食物ID列表
    const foodIds = matchedRecipeFoods.map(rf => rf.food_id);
    
    // 获取食物详情（注意接口路径为 food/all）
    return axios.get(`http://localhost:8080/MDMS0214_war/food/all`)
      .then(foodRes => {
        const foodMap = new Map(foodRes.data.map(f => [f.food_id, f]));
        
        // 整理最终展示数据
        usedFoods.value = matchedRecipeFoods.map(rf => {
          const food = foodMap.get(rf.food_id);
          return {
            foodName: food?.name || '未知食物',
            quantity: rf.quantity,
            unit: '克', // 可根据实际数据调整单位（当前接口未返回，默认设为克）
            processingMethod: rf.processing_method || '未说明'
          };
        });
        
        loading.value = false;
      });
  })
  .catch(err => {
    console.error('数据获取失败:', err);
    error.value = '抱歉，无法加载食谱详情，请稍后重试';
    loading.value = false;
  });

// 图片错误处理
const handleImageError = () => {
  imageError.value = true;
  console.log('图片加载失败，尝试使用默认图');
};
</script>

<style scoped>
.shipudetail {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    width: 80%;
    max-width: 500px;
    position: relative;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.close-btn {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #888;
    transition: color 0.2s;
}

.close-btn:hover {
    color: #333;
}

.food-info {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.food-image-container {
    display: flex;
    justify-content: center;
    align-items: center;
    border: 2px solid #ff4d4f;
    border-radius: 4px;
    padding: 5px;
    min-height: 150px;
    background-color: #f5f5f5;
}

.food-image {
    max-width: 100%;
    max-height: 200px;
    object-fit: contain;
    transition: transform 0.2s;
}

.food-image:hover {
    transform: scale(1.05);
}

.nutritional-info {
    padding: 10px 0;
}

.nutritional-info p {
    margin: 8px 0;
    line-height: 1.5;
}

.used-foods {
    margin-top: 15px;
}

.used-foods h4 {
    margin-bottom: 5px;
}

.used-foods ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

.used-foods li {
    margin-bottom: 3px;
}

.empty-foods {
    color: #999;
    font-style: italic;
}

.loading {
    text-align: center;
    color: #666;
    padding: 20px;
}

.error {
    text-align: center;
    color: #ff4d4f;
    padding: 20px;
}
</style>